package com.dnndo.common.core.page;

import com.dnndo.common.core.text.Convert;
import com.dnndo.common.utils.ServletUtils;
import jakarta.servlet.http.HttpServletRequest;

/**
 * 表格数据处理
 * 
 * @author ruoyi
 */
public class TableSupport
{
    /**
     * 当前记录起始索引
     */
    public static final String PAGE_NUM = "pageNum";

    /**
     * 每页显示记录数
     */
    public static final String PAGE_SIZE = "pageSize";

    /**
     * 排序列
     */
    public static final String ORDER_BY_COLUMN = "orderByColumn";

    /**
     * 排序的方向 "desc" 或者 "asc".
     */
    public static final String IS_ASC = "isAsc";

    /**
     * 分页参数合理化
     */
    public static final String REASONABLE = "reasonable";

    /**
     * 封装分页对象
     */
    public static PageDomain getPageDomain() {
        PageDomain pageDomain = new PageDomain();
        HttpServletRequest request = ServletUtils.getRequest();

        // 获取分页参数，处理 Integer 和 String 类型
        Object pageNumObj = request.getAttribute(PAGE_NUM);
        Object pageSizeObj = request.getAttribute(PAGE_SIZE);

        String pageNumStr = null;
        String pageSizeStr = null;

        // 处理 pageNum
        if (pageNumObj != null) {
            if (pageNumObj instanceof Integer) {
                pageNumStr = String.valueOf(pageNumObj);
            } else if (pageNumObj instanceof String) {
                pageNumStr = (String) pageNumObj;
            }
        }

        // 处理 pageSize
        if (pageSizeObj != null) {
            if (pageSizeObj instanceof Integer) {
                pageSizeStr = String.valueOf(pageSizeObj);
            } else if (pageSizeObj instanceof String) {
                pageSizeStr = (String) pageSizeObj;
            }
        }

        // 如果从属性中没有获取到，尝试从参数中获取
        if (pageNumStr == null) {
            pageNumStr = request.getParameter(PAGE_NUM);
        }
        if (pageSizeStr == null) {
            pageSizeStr = request.getParameter(PAGE_SIZE);
        }

        pageDomain.setPageNum(Convert.toInt(pageNumStr, 1));
        pageDomain.setPageSize(Convert.toInt(pageSizeStr, 10));

        // 其他参数保持不变
        pageDomain.setOrderByColumn(request.getParameter(ORDER_BY_COLUMN));
        pageDomain.setIsAsc(request.getParameter(IS_ASC));
        pageDomain.setReasonable(ServletUtils.getParameterToBool(REASONABLE));

        return pageDomain;
    }



    public static PageDomain buildPageRequest()
    {
        return getPageDomain();
    }
}
